﻿
CREATE PROCEDURE [dbo].[ShiftOutLinesUpdate]
(
	@Qntty int,
	@RetailSum decimal(19, 2),
	@Note varchar(250),
	@MD datetime,
	@MW varchar(50),
	@Original_Id int,
	@Original_MD datetime
)--строка по расходной накладной на внутренее перемещение. Нельзя менять партиию
AS
DECLARE @strMsg nvarchar(500), @intRet int, @intErrCode int
DECLARE @intGoodsId int, @intDocTypeId int, @orgQntty int
DECLARE @orgDocDate smalldatetime, @orgPartyId int
DECLARE @intInputCount int, @intOutputCount int

SET NOCOUNT ON
IF (@Original_Id Is Null) OR (@Original_MD Is Null) OR (@Qntty Is Null) OR (@RetailSum Is Null)
BEGIN
	SELECT @intErrCode = 1, @strMsg = 'Неправильные параметры в вызове процедуры ' + Object_Name(@@Procid) + ' !'
	RAISERROR (@strMsg, 11, 1)
	RETURN @intErrCode
END

IF (@Qntty <=0) OR (@RetailSum <=0)
BEGIN
	SELECT @intErrCode = 2, @strMsg = 'Количество и сумма д.б. больше нуля !'
	RAISERROR (@strMsg, 11, 1)
	RETURN @intErrCode
END

SELECT @orgDocDate = D.DocDate, @intDocTypeId = D.DocTypeId, @orgQntty = L.Qntty,
@orgPartyId = PartyId
FROM [CA].[GoodsDocLines] L INNER JOIN [CA].[Documents] D ON D.Id = L.DocId
WHERE L.Id = @Original_Id AND L.MD = @Original_MD
IF (@@rowcount <> 1)
BEGIN
	SELECT @intErrCode = 3, 
	@strMsg = 'Данные изменены после последнего запроса!'
	RAISERROR (@strMsg, 11, 1)
	RETURN @intErrCode
END

IF (@intDocTypeId <> 4)
BEGIN
	SELECT @intErrCode = 4, @strMsg = 'Неправильный тип документа с идентификатором!'
	RAISERROR (@strMsg, 11, @intErrCode)
	RETURN @intErrCode
END

SELECT @intGoodsId = GoodsId FROM CD.Parties WHERE Id = @orgPartyId
IF [dbo].[CheckQuarantineForGoods](@intGoodsId) <> 0  
BEGIN
	SELECT @intErrCode = 5, 
	@strMsg = 'Товар с идентификатором ' + cast(@intGoodsId as varchar(20)) + ' находится в карантине!'
	RAISERROR (@strMsg, 11, 1)
	RETURN @intErrCode
END

--проверка товародвижения
SET @intErrCode = @Qntty + @orgQntty
IF @intErrCode < 0
BEGIN
	EXEC @intRet = dbo.CheckPartyFlow @orgPartyId, @intErrCode, @orgDocDate, @intInputCount OUTPUT, @intOutputCount OUTPUT
	IF @intRet <> 0 RETURN @intRet
END

EXEC [dbo].[ProcessStatistic] @Note OUTPUT, @MD OUTPUT, @MW OUTPUT

	SET NOCOUNT OFF;
UPDATE [CA].[GoodsDocLines] SET 
[Qntty] = 0 - @Qntty, [RetailSum] = 0.0 - @RetailSum,
[Note] = @Note, [MD] = @MD, [MW] = @MW 
WHERE Id = @Original_Id AND MD = @Original_MD;

SELECT L.Id, L.DocId, L.PartyId, 
L.Qntty * (-1) AS Qntty, L.RetailSum * (-1.0) AS RetailSum, L.ReturnLineId,
L.Note, L.MD, L.MW 
FROM CA.GoodsDocLines AS L WHERE L.Id = @Original_Id
RETURN 0
